package com.gxwgy.wg2404.controller;

import com.gxwgy.wg2404.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.*;

/**
 * @author 姚相国
 * @version 1.0
 * @className UserServlet
 * @date 2024/12/17 23:18
 */
@WebServlet({"/user/login","/user/register"})
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取servlet路径
        String servletPath = request.getServletPath();
        if ("/user/login".equals(servletPath)) {
            doLogin(request, response);
        } else if ("/user/add".equals(servletPath)) {
            doRegister(request,response);
        }
    }

    // 登录逻辑
    // 登录逻辑
    private void doLogin(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        // 设置编码
        request.setCharacterEncoding("UTF-8");
        // 获取用户名密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 连接数据库查询比对
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();

            if (rs.next()) {
                // 登录成功
                // 获取角色信息
                String role = rs.getString("role");
                Integer userId = rs.getInt("id");

                // 创建session对象，保存用户名和角色
                HttpSession session = request.getSession();
                session.setAttribute("userId", userId);
                session.setAttribute("username", username);
                session.setAttribute("role", role);  // 保存角色信息

                // 根据角色跳转到不同的页面
                if ("admin".equals(role)) {
                    response.sendRedirect(request.getContextPath() + "/admin/dashboard");
                } else if ("organizer".equals(role)) {
                    response.sendRedirect(request.getContextPath() + "/organizer/dashboard");
                } else {
                    response.sendRedirect(request.getContextPath() + "/activity/list");
                }
            } else {
                // 登录失败
                response.sendRedirect(request.getContextPath() + "/error.jsp");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn, ps, rs);
        }
    }


    // 注册逻辑
    private void doRegister(HttpServletRequest request, HttpServletResponse response) {
        // 获取参数
        String email = request.getParameter("email");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = "user"; // 默认角色是普通用户

        // 注册时间使用后端生成
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        String datatime = String.valueOf(currentTime);

        // 连接数据库执行insert语句
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO users(username, password, email, role, created_at, updated_at) VALUES(?, ?, ?, ?, ?, ?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ps.setString(3, email);
            ps.setString(4, role);  // 插入默认角色
            ps.setString(5, datatime);
            ps.setString(6, datatime);
            ps.executeUpdate();

            // 提示成功并跳转到登录页面
            response.setContentType("text/html; charset=UTF-8");
            response.getWriter().println("<script>alert('注册成功！即将跳转到登录页面'); location.href='"+request.getContextPath()+"';</script>");
        } catch (SQLException | IOException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn, ps, null);
        }
    }

}
